﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace SmartSpace.Core
{
    public static class EntityRepository
    {
        public static bool Save<TEntity>(TEntity entity, DbContext context) where TEntity : class, IGuidKeyEntity
        {
            if (context.Set<TEntity>().Where(p => p.Id == entity.Id)
                .Select(p => p.Id).SingleOrDefault() == default(Guid))
            {
                context.Set<TEntity>().Add(entity);
            }
            else
            {
                context.Entry(entity).State = EntityState.Modified;
            }

            if (context.SaveChanges() > 0)
            {
                return true;
            }
            return false;
        }

        public static bool Delete(IGuidKeyEntity entity, DbContext context)
        {
            if (context.Set<IGuidKeyEntity>().Where(p => p.Id == entity.Id)
                .Select(p => p.Id).SingleOrDefault() == default(Guid))
            {
                return true;
            }
            else
            {
                context.Entry(entity).State = EntityState.Deleted;
            }

            if (context.SaveChanges() > 0)
            {
                return true;
            }
            return false;
        }

        public static bool Delete(Guid entityId, DbContext context)
        {
            IGuidKeyEntity entity = context.Set<IGuidKeyEntity>().Where(p => p.Id == entityId).SingleOrDefault();
            if (entity == null)
            {
                return true;
            }
            else
            {
                context.Entry(entity).State = EntityState.Deleted;
            }

            if (context.SaveChanges() > 0)
            {
                return true;
            }
            return false;
        }

        public static IGuidKeyEntity Get(Guid entityId, DbContext context)
        {
            return context.Set<IGuidKeyEntity>().Where(p => p.Id == entityId).Single();
        }
    }
}
